﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Enterprise.Framework.DomainModel;
using Enterprise.Framework.DomainModel.Repositories;
using Enterprise.Framework.Core.Exceptions;
using Resto.CostControl.Core.Domain.Resource;
using Resto.CostControl.Common.Utility;

namespace Resto.CostControl.Core.Domain.Model
{
     /// <summary>
    /// 字典
    /// </summary>
    public partial class Dictionary : IAggregationRoot
    {
        #region 构造函数

        internal Dictionary()
        {
            this.ID = IDHelper.CreateNewID();
        }

        #endregion

        #region 私有属性

        private IEntityRepository<Dictionary> _Repository;
        protected IEntityRepository<Dictionary> Repository
        {
            get
            {
                if (_Repository == null)
                    _Repository = RestoCostDomainSession.CurrentSession.CreateEntityRepository<Dictionary>();

                return _Repository;
            }
        }

        #endregion


        #region 业务方法

        public void Add()
        {
            Validate();

            Repository.Add(this);
        }

        public void Update()
        {
            Validate();

            Repository.Update(this);
        }

        public void Delete()
        {
            Repository.Delete(this);
        }

        #endregion

        #region 验证方法

        private void Validate()
        {
            List<string> messageList = new List<string>();

            ValidateCodeRepeat(messageList);

            if (messageList.Count > 0)
                throw new BusinessValidationException(messageList.ToArray());
        }

        private void ValidateCodeRepeat(IList<string> messageList)
        {
            IEnumerable<Dictionary> list = from o in Repository.Objects
                                           where o.ID != ID
                                           && o.Code == Code
                                           && o.TypeCode == this.TypeCode
                                           select o;

            bool result = list.Count() > 0;
            if (result)
                messageList.Add(string.Format(DictionaryResource.ValidateException_DictionaryCode_Repeat_ByDictionaryType, Code));
        }


        #endregion
    }
}
